# -*- coding: utf-8 -*-

import re, json

class BabyCryPredictor:
    # 对新的音频信号进行分类并确定它是否是婴儿哭声
    def __init__(self, model):
        self.model = model

    def classify(self, new_signal):
        """
        使用训练好的模型进行预测
        :param new_signal: 一维数组，34 个特征
        :return: 1（是婴儿哭声）；0（不是婴儿哭声）
        """
        category = self.model.predict(new_signal)
        # category is an array of the kind array(['004 - Baby cry'], dtype=object)
        return self._is_baby_cry(category[0])

    @staticmethod
    def _is_baby_cry(string: str):
        """
        字符串分析，检测是否属于婴儿哭声类别
        :param string: 模型预测输出的字符串
        :return: 1（是婴儿哭声）；0（不是婴儿哭声）
        """
        # 属于这里面的都是哭
        infos = {
            "301":"哭闹",
            "904":"醒了",
            "905":"宝宝要换尿布",
            "906":"要抱抱", 
            "907":"宝宝饿了", 
            "908":"要睡觉", 
            "909":"哭闹未分类",
        }
        print(string)
        cry_labs = ["301", "904", "905", "906", "907", "908", "909"]
        lable = string.split(" - ")[0]
        state = 1 if lable in cry_labs else 0
        if state == 1:
            return state, infos.get(lable)
        else:
            return state, "noise"
        
class MajorityVoter:
    # 类别对多个（5 个或更多？无论如何是奇数）分类进行多数投票
    def __init__(self, prediction_list):
        # self.predictions = prediction_list
        self.predictions = []
        self.ones = []
        self.zeros = []
        
        for p, l in prediction_list:
            self.predictions.append(p)
            if p == 0:
                self.zeros.append(l)
            elif p == 1:
                self.ones.append(l)
        
    # 总体预测如果超过一半的预测结果为 1，则返回 1
    def vote(self):
        if sum(self.predictions) > len(self.predictions)/2.0:
            return 1, self.ones[0]
        else:
            return 0, self.zeros[0]
